import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * XLog 转码工具
 */
public class DecodeTool {
    public static void main(String[] args) {
        // 创建JFrame
        JFrame frame = new ToolLayout();
        // 设置尺寸
        frame.setSize(800, 300);
        // JFrame在屏幕居中
        frame.setLocationRelativeTo(null);

        // JFrame关闭时的操作
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 显示JFrame
        frame.setVisible(true);

    }

    static class ToolLayout extends JFrame {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
        JTextArea outPutTextArea = new JTextArea();
        public ToolLayout() {
//            setLayout(new GridLayout(3, 1));
            setLayout(new BorderLayout());
            setTitle("XLog 转码工具");
            initLayout();
        }

        private void initLayout() {
            JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
            panel1.add(new JLabel("输出:"));
            add(panel1, BorderLayout.NORTH);


            outPutTextArea.setEnabled(false);
            outPutTextArea.setLineWrap(true);//激活自动换行功能
            outPutTextArea.setWrapStyleWord(true);// 激活断行不断字功能


            JScrollPane jScrollPaneInfo = new JScrollPane(outPutTextArea);
            add(jScrollPaneInfo);

            //自动更新?
            DefaultCaret caret = (DefaultCaret) outPutTextArea.getCaret();
            caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

            if (isSelectedPythonFile()) {
                log("点击选择需要解码的 xLog 文件");
            } else {
                log("请先选择解码脚本!!!");
            }

            JButton selectXLogFileButton = new JButton("点击选择 xLog 文件");
            selectXLogFileButton.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    super.mouseClicked(e);
                    if (isSelectedPythonFile()) {
                        selectXLogFile();
                    } else {
                        log("请先选择解码脚本!!!");
                    }
                }
            });

            JButton pythonFilePath = new JButton("选取 xLog 解码脚本路径(只有首次需要)");
            pythonFilePath.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    super.mouseClicked(e);
                    selectPythonFile();
                }
            });
            JPanel panel2 = new JPanel(new FlowLayout());
            panel2.add(selectXLogFileButton);
            panel2.add(pythonFilePath);
            add(panel2, BorderLayout.SOUTH);
        }

        private void selectXLogFile() {
            //动态获取保存文件路径
            JFileChooser fileChooser = new JFileChooser();
            FileSystemView fsv = FileSystemView.getFileSystemView();     //注意了，这里重要的一句
            //System.out.println(fsv.getHomeDirectory());                  //得到桌面路径
            //设置展示路径
            fileChooser.setCurrentDirectory(new File(
                    KVStorage.get("xLogPath", fsv.getHomeDirectory().getPath())
            ));
            fileChooser.setDialogTitle("请选择要解码的文件");
            fileChooser.setApproveButtonText("确定");
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.getName().endsWith(getDescription()) || f.isDirectory();
                }

                @Override
                public String getDescription() {
                    return ".xlog";
                }
            });
            int result = fileChooser.showOpenDialog(null);
            if (JFileChooser.APPROVE_OPTION == result) {
                String xLogFilePath = fileChooser.getSelectedFile().getPath();
                log("xLog Path: " + xLogFilePath);
                KVStorage.put("xLogPath", new File(xLogFilePath).getParent());

                String pythonFilePath = KVStorage.get("PythonFilePath", "");
                if (pythonFilePath.isEmpty()) {
                    log("请先指定 xLog 转码脚本!");
                } else {
                    String command = "python" + " "+ pythonFilePath + " "+ xLogFilePath;
                    log("invoke : " + command);
                    ShellExecUtil.run(this::log, "python", pythonFilePath, xLogFilePath);
                    log("执行完成!");
                }

            }
        }

        private void selectPythonFile() {
            //动态获取保存文件路径
            JFileChooser fileChooser = new JFileChooser();
            FileSystemView fsv = FileSystemView.getFileSystemView();     //注意了，这里重要的一句
            //System.out.println(fsv.getHomeDirectory());                  //得到桌面路径
            //设置展示路径
            fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
            fileChooser.setDialogTitle("选取 xLog 解码脚本路径");
            fileChooser.setApproveButtonText("确定");
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.getName().endsWith(getDescription()) || f.isDirectory();
                }

                @Override
                public String getDescription() {
                    return ".py";
                }
            });
            int result = fileChooser.showOpenDialog(null);
            if (JFileChooser.APPROVE_OPTION == result) {
                String path = fileChooser.getSelectedFile().getPath();
                log("Python File Path: " + path);
                KVStorage.put("PythonFilePath", path);
            }
        }

        private boolean isSelectedPythonFile() {
            return !KVStorage.get("PythonFilePath", "").trim().isEmpty();
        }

        public void log(String msg) {
            msg = msg.trim();
            if (msg.isEmpty()) {
                return;
            }
            Date date = new Date(System.currentTimeMillis());
            outPutTextArea.append(sdf.format(date) + " " + msg + "\n");
            System.out.println(msg);
        }
    }

}
